package com.atguigu.schedule.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseController<T> extends HttpServlet {
    private Class<T> clazz;
    {
        // 这段代码会在子类对象构造时执行，作用是给clazz赋值为泛型指定类型
        Type genericSuperClass = this.getClass().getGenericSuperclass();// 带泛型的父类
        ParameterizedType parameterizedType = (ParameterizedType) genericSuperClass;
        Type[] typeArgs = parameterizedType.getActualTypeArguments();// 获取了父类的泛型参数
        clazz = (Class<T>) typeArgs[0];// 泛型的第一个参数
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        String[] spArr = uri.split("/");
        String method = spArr[spArr.length - 1];

        // 通过 反射 直接调用方法
//        Class clazz = this.getClass();
        try {
            Method method1 = this.clazz.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            method1.setAccessible(true);
            method1.invoke(this, req, resp);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
